package com.example.instagram.service;

import com.example.instagram.vo.CodeVo;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: dangwen
 * @createDate: 2021/3/8
 */
@Slf4j
@Service
public class ActionService {

    private static String redirectUri = "https://accesstofb.easemob.com/ins/code";
    private static String clientId = "144209597573899";
    private static String clientSecret = "76cae13349723b554897ce76c3de8fca";

    @Resource
    private RestTemplate restTemplate;
    /**第一步：获取授权：144209597573899
     * https://api.instagram.com/oauth/authorize
     *   ?client_id={instagram-app-id}
     *   &redirect_uri={redirect-uri}
     *   &scope={scope}
     *   &response_type=code
     *   &state={state}        //Optional
     */
    public String insAuthorize() {

        String authUrl = "https://api.instagram.com/oauth/authorize?client_id="+clientId+"&redirect_uri=" + redirectUri +
                "&scope=user_profile,user_media&response_type=code";
        log.info("----------authUrl: {}", authUrl);
        return authUrl;
    }

    /**
     * 去除掉 "#_"+
     */
    public void getCode(CodeVo codeVo){
        log.info("-----------codeVo: {}", codeVo.toString());
        String code = codeVo.getCode();
        if(!StringUtils.isEmpty(code)){
            // 这里是我们需要的code
            String realCode = code.replace("#_", "");
            // 收到代碼後，向以下端點傳送 POST 要求，以用它獲取短期存取憑證
            // POST https://api.instagram.com/oauth/access_token
            // String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables
            String url = "https://api.instagram.com/oauth/access_token";
            Map<String,String> map = new HashMap<>();
            map.put("client_id",clientId);
            map.put("client_secret",clientSecret);
            map.put("code",realCode);
            map.put("grant_type","authorization_code");
            map.put("redirect_uri",redirectUri);
            ResponseEntity<Map> mapResponseEntity = restTemplate.postForEntity(url, map, Map.class);
            log.info("-------------------mapResponseEntity: {}",mapResponseEntity.toString());
            Map bodyMap = mapResponseEntity.getBody();
            // 擷取 access_token 值。這是用戶的短期 Instagram 存取憑證，您的應用程式可它來存取 Instagram 基本顯示 API 端點。
            // 默认情况下，Instagram 用户访问口令是短期访问口令，仅在 1 小时内有效。但短期口令可以交换为长期口令,长期口令有效期为 60 天
            String accessToken = (String) bodyMap.get("access_token");
            String userId = null;
            if(!StringUtils.isEmpty(accessToken)){
                userId = (String) bodyMap.get("user_id");
            }else {
                String errorType = (String) bodyMap.get("error_type");
                String errorCode = (String) bodyMap.get("code");
                String errorMessage = (String) bodyMap.get("error_message");
            }
            // 换取长期口令
            // https://graph.instagram.com/access_token?grant_type=ig_exchange_token &client_secret={instagram-app-secret} &access_token={short-lived-access-token}
            String tokenUrl = "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret="+clientSecret+"&access_token="+accessToken;
            Map tokenMap = restTemplate.getForObject(tokenUrl,Map.class);
            log.info("-------------------tokenMap: {}",tokenMap.toString());
            // { "access_token":"{long-lived-user-access-token}", "token_type": "bearer", "expires_in":5183944 // 此口令保持有效的秒数}
            String longAccessToken= (String) tokenMap.get("access_token");
            String tokenType = (String) tokenMap.get("token_type");
            String expiresIn = (String) tokenMap.get("expires_in");

            // 获取用户信息get
            // https://graph.instagram.com/{user-id}?fields={fields}&access_token={access-token}
            if(userId != null){
                String userInfoUrl = "https://graph.instagram.com/"+userId+"?fields=account_type,id,media_count,username,media&access_token="+accessToken;
                // { "{field}":"{value}", ... }
                Map userInfoMap = restTemplate.getForObject(userInfoUrl, Map.class);
                log.info("-------------------userInfoMap: {}",userInfoMap.toString());
                String accountType = (String) userInfoMap.get("account_type");
                String id = (String) userInfoMap.get("id");
                String mediaCount = (String) userInfoMap.get("media_count");
                String username = (String) userInfoMap.get("username");
                String media = (String) userInfoMap.get("media");

            }
        }
        System.out.println("----------------------------------function getCode work done!");
    }

    // "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token &access_token={long-lived-access-token}"
    public void flushToken(String oldToken){
        String url = "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token="+oldToken;
        Map resultMap = restTemplate.getForObject(url, Map.class);
        // { "access_token":"{long-lived-user-access-token}", "token_type": "bearer", "expires_in":5183944 // 此口令保持有效的秒数}
        String newToken = (String) resultMap.get("access_token");
        String tokenType = (String) resultMap.get("token_type");
        String expiresIn = (String) resultMap.get("expires_in");
        log.info("-------------------resultMap: {}",resultMap.toString());
    }


}
